<template>
  <vPage>
    <v-form ref="formRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-form
          class="vx-table__form-content"
          :model="form"
          label-align="right"
          label-width="100"
          size="default"
          label-position="top"
        >
          <el-date-picker
            v-model="form.performance_month"
            type="month"
            value-format="YYYY-MM-DD"
            placeholder="请选择绩效月份"
          />
          <el-date-picker
            v-model="form.assignment_time_start"
            type="week"
            format="第 ww 周"
            placeholder="选择周"
            value-format="YYYY-MM-DD"
            :picker-options="{ firstDayOfWeek: 1 }"
            :clearable="false"
            :start-date="startDate"
          />
          <VGroup>
            <el-select class="selectClass !w-[120px]" v-model="form.productName.type">
              <el-option label="SKU" value="sku"></el-option>
              <el-option label="SPU" value="spu"></el-option>
              <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            </el-select>
            <multi-input
              clearable
              v-model="form.productName.value"
              style="width: 180px"
              placeholder="批量搜索,一行一个"
            ></multi-input>
          </VGroup>
          <multi-input
            clearable
            v-model="form.task_no"
            style="width: 200px"
            placeholder="任务单号,批量搜索,一行一个"
          ></multi-input>

          <el-select
            v-model="form.status"
            class="!w-[200px]"
            placeholder="任务状态"
            multiple
            clearable
            collapse-tags
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <VGroup>
            <el-select
              class="selectClass !w-[160px]"
              v-model="form.dateRange.type"
              collapse-tags
              placeholder="创建时间"
            >
              <el-option
                v-for="item in dateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-model="form.dateRange.value"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime()"
            />
          </VGroup>
          <el-select
            v-model="form.priority"
            collapse-tags
            placeholder="优先级"
            clearable
            class="!w-[120px]"
            multiple
          >
            <el-option
              v-for="item of options['assignment.ImagesAssignment']?.[0].priorityText"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="form.is_delay"
            class="!w-[160px]"
            placeholder="是否延期"
            clearable
          >
            <el-option
              v-for="item in options['assignment.ImagesAssignment']?.[0].isDelayText"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <VGroup>
            <el-select class="selectClass !w-[120px]" v-model="form.personnelRange.type">
              <el-option
                v-for="item in userOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <select-personnel
              v-model="form.personnelRange.value"
              :multiple="true"
              placeholder="请选择"
            ></select-personnel>
          </VGroup>
          <el-select
            v-model="form.pid"
            class="!w-[160px]"
            placeholder="是否子任务"
            clearable
          >
            <el-option
              v-for="item in subTaskOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <div class="vx-table__form-handle">
            <el-button type="primary" @click="query">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-form>
      </template>
    </v-form>
    <el-tabs v-model="activeName" type="card" class="px-4 mt-1" @tab-click="handleClick">
      <el-tab-pane
        :label="item.user_name"
        :name="item.user_id"
        v-for="(item, index) in personnel_list"
        :key="index"
      ></el-tab-pane>
    </el-tabs>

    <div class="px-4" ref="tableBoxRef">
      <el-table
        class="draggable"
        ref="tableRef"
        :data="tableData"
        row-key="id"
        border
        fit
        :height="height"
        style="width: 100%"
        :loading="loading"
        :row-class-name="rowClassName"
      >
        <!-- 拖拽 -->
        <el-table-column align="center" label="处理顺序" width="120">
          <template #default="{ row }">
            <div class="flex items-center">
              <svg-icon
                class="mr-1 text-[#999999] text-lg"
                icon-class="tuodong"
              ></svg-icon>
              <el-input
                v-model="row.images_user_task.handle_sort"
                oninput="value=value.replace(/[^0-9]/g,'')"
                @blur="changeUserRow(row)"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="处理日期" width="180">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.images_user_task.handle_time"
              type="date"
              placeholder="处理日期"
              style="width: 150px"
              value-format="YYYY-MM-DD"
              @change="changeUserRow(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="task_no" label="任务单号" width="180">
          <template #default="{ row }">
            <div :class="['font-size-10px', `taskBgColor${row.status}`]">
              {{ row.status_text }}
            </div>
            <div :class="['font-size-10px', 'ml-4', `priorityBgColor${row.priority}`]">
              {{ row.priority_text }}
            </div>
            <div class="flex">
              <VText
                type="button"
                :value="row.task_no"
                :copy="true"
                @click="pictureTaskFun('view', row.id)"
              >
              </VText>
              <el-tooltip
                v-if="row.pid"
                class="item"
                effect="dark"
                :content="row.belongs_task?.task_no"
                placement="top"
              >
                <div class="bg-[#E50113] text-[#fff] w-5 h-5 rounded-full text-center">
                  子
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="is_finsh" label="是否分配周期内完成" width="160">
          <template #default="{ row }">
            {{ comparisonTime(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="sku" label="SKU" width="160">
          <template #default="{ row }">
            {{ row.images_assignment_sku.map((i) => i.sku).join("、") }}
          </template>
        </el-table-column>
        <el-table-column prop="task_priority_text" label="任务等级/类型" width="180">
          <template #default="{ row }">
            <div v-if="row.task_priority_text">
              <span
                :class="`bgColor${row.task_priority_text}`"
                style="text-align: center; height: 20px; padding: 0 6px"
                >{{ row.task_priority_text }}</span
              >
            </div>
            <div class="overflow-line2 text-[#333333]">
              <el-tooltip
                class="item"
                effect="dark"
                :content="row.task_type_text_export"
                placement="top"
              >
                <span class="flex-1"> {{ row.task_type_text_export }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="priority_text" label="任务优先级" width="110">
        </el-table-column>
        <el-table-column prop="address" label="任务处理人" width="180">
          <template #default="{ row }">
            <div class="" v-if="row.designer_user_text">
              图片处理人员：{{ row.designer_user_text }}
            </div>
            <div class="" v-if="row.photography_user_text">
              摄影人员：{{ row.photography_user_text }}
            </div>
            <div class="" v-if="row.edit_user_text">
              编辑人员：{{ row.edit_user_text }}
            </div>
            <div class="" v-if="row.render_user_text">
              渲染人员：{{ row.render_user_text }}
            </div>
            <div class="" v-if="row.assistance_user_text">
              协助人员：{{ row.assistance_user_text }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="task_remark" label="处理人备注" width="180">
          <template #default="{ row }">
            <el-input
              v-model="row.handle_remark"
              type="textarea"
              placeholder="处理人备注"
              :autosize="{ minRows: 2, maxRows: 2 }"
              @blur="changeTaskRow(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="converted_quantity" label="目标套数" width="180">
          <template #default="{ row }">
            <el-input
              v-model="row.converted_quantity"
              placeholder="目标套数"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
              @blur="changeTaskRow(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="is_exceed_task" label="是否超额任务" width="120">
          <template #default="{ row }">
            <el-switch
              v-model="row.is_exceed_task"
              :active-value="1"
              :inactive-value="0"
              :disabled="disabled"
              @change="changeTaskRow(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="score" label="绩效分值" width="100"></el-table-column>
        <el-table-column prop="uploaded_image_count" label="图片数量" width="100">
          <template #default="{ row }">
            <div class="mr-2">
              <span class="text-[#3366f1] cursor-pointer" @click="checkImageFun(row)"
                >{{ row.uploaded_image_count || 0 }} 张</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_user" label="创建人" width="160">
          <template #default="{ row }">
            <div>{{ row.create_user_text || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="assignment_time_start"
          label="部门分配开始时间"
          width="180"
        >
          <template #default="{ row }">
            <div>{{ row.assignment_time_start || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="assignment_time_end" label="部门分配结束时间" width="180">
          <template #default="{ row }">
            <div>{{ row.assignment_time_end || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="performance_month" label="绩效月份" width="120">
          <template #default="{ row }">
            <div>{{ row.performance_month || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180">
          <template #default="{ row }">
            <div>{{ row.create_time || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="process_time" label="提交审核时间" width="180">
          <template #default="{ row }">
            <div>{{ row.process_time || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="designer_time" label="设计审核时间" width="180">
          <template #default="{ row }">
            <div>{{ row.designer_time || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="operators_time" label="运营审核时间" width="180">
          <template #default="{ row }">
            <div>{{ row.operators_time || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="expected_time" label="预期完成时间" width="180">
          <template #default="{ row }">
            <div>{{ row.expected_time || "--" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <template v-if="row.status != 6">
              <VButton
                auth="/goods/task/picture/edit"
                link
                type="primary"
                @click="pictureTaskFun('edit', row.id)"
                >编辑
              </VButton>
            </template>
            <VButton
              auth="/goods/task/picture/taskClaim"
              type="primary"
              link
              @click.prevent="handleClaimTask(row)"
              >任务认领
            </VButton>
            <template v-if="row.status == 2 || row.status == 8">
              <VButton
                auth="/goods/task/picture/sumitAudit"
                type="primary"
                link
                @click="handleBatch('haveReviewed', row)"
                >提交审核
              </VButton>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </vPage>
  <addTaskConption ref="refAddTask" @query="queryForm" />
  <checkImage ref="refCheckImage" :imgList="imgList" />
  <pictureDialogConption ref="diaLog" @query="queryForm"></pictureDialogConption>
</template>
<script name="TaskPictureTask-board-electronics" setup lang="jsx">
import { nextTick, onMounted, ref, toRefs, computed } from "vue";
import { getOptions } from "@/api/index";
import VForm from "@/components/VForm/index.vue";
import { subTaskOptions, userOptions, dateOptions, statusOptions } from "./data.js";
import { Sortable } from "sortablejs";
import addTaskConption from "../picture/components/addTask.vue";
import {
  getDataboardUserList,
  getDataboardElectronicList,
  userTaskInfo,
  editTaskInfo,
  eletronicSort,
  imagesAssignmentClaimTask,
  // claimTask,
} from "../picture/api/index.js";
import { ElMessage } from "element-plus";
import {
  getCurrentWeek,
  getFirstDayOfMonthString,
  getLastDayOfMonthString,
} from "@/utils/index.js";
import checkImage from "../picture/components/checkImage.vue";
import pictureDialogConption from "../picture/components/pictureDialog.vue";

const height = computed(() => {
  return `calc(100vh - 260px)`;
});

const disabled = computed(() => {
  return !(window.BTN_AUTH || []).includes("/goods/task/picture/setExcessTask");
});

const tableOptins = reactive({
  formConfig: {
    productName: { type: "sku", value: "" },
    dateRange: { type: "create_time", value: [], range: true },
    personnelRange: { type: "create_user", value: [], range: false },
    assignment_time_start: getCurrentWeek(),
    status: [1, 2, 8, 3, 4, 5],
  },
});

// 下拉数据
const fetchOption = () => {
  getOptions({ name: ["assignment.ImagesAssignment", "assignment.ImagesTag"] }).then(
    (res) => {
      if (res.data["assignment.ImagesAssignment"][0].priorityText.length) {
        res.data["assignment.ImagesAssignment"][0].priorityText02 = res.data[
          "assignment.ImagesAssignment"
        ][0].priorityText.map((i) => {
          if (i.value == 1) {
            i.label = i.label + "(非常紧急)";
          } else if (i.value == 2) {
            i.label = i.label + "(紧急)";
          } else if (i.value == 3) {
            i.label = i.label + "(正常)";
          }
          return i;
        });
      }
      options.value = res.data;
    }
  );
};

const data = reactive({
  options: {},
  tabList: [
    {
      label: "全部",
      name: "",
      count: 0,
    },
    {
      label: "待分配人员",
      name: 1,
      count: 0,
    },
    {
      label: "待处理",
      name: 2,
      count: 0,
    },
    {
      label: "待设计审核",
      name: 3,
      count: 0,
    },
    {
      label: "待运营审核",
      name: 4,
      count: 0,
    },
    {
      label: "审核未通过",
      name: 5,
      count: 0,
    },
    {
      label: "已完成",
      name: 6,
      count: 0,
    },
    {
      label: "已取消",
      name: 7,
      count: 0,
    },
  ],
  tableData: [],
  personnel_list: [],
  activeName: "",
  loading: false,
});

const { options, tableData, personnel_list, activeName, loading } = toRefs(data);

provide("options", options);

onMounted(async () => {
  fetchOption();
  initSort();
});

// 行拖拽
const tableRef = ref();
const tableBoxRef = ref();
const initSort = () => {
  const el = tableBoxRef.value.querySelector(".el-table__body-wrapper tbody");
  Sortable.create(el, {
    animation: 150, // 动画
    onEnd: (event) => {
      if (event.oldIndex !== undefined && event.newIndex !== undefined) {
        const curRow = tableData.value.splice(event.oldIndex, 1)[0];
        tableData.value.splice(event.newIndex, 0, curRow);
        console.log(event.oldIndex, event.newIndex);
        handleSort();
      }
    },
  });
};

const formRef = ref();
const query = () => {
  const form = formRef.value.getForm();
  formRef.value.setForm({
    user_id: activeName.value,
    ...form,
  });
  queryForm();
};

const resetForm = () => {
  formRef.value.setForm({
    user_id: activeName.value,
  });
  queryForm();
};

// 新增/编辑
const refAddTask = ref();
const pictureTaskFun = (type, id) => {
  nextTick(() => {
    refAddTask?.value.open(type, id);
  });
};

const handleClick = (val) => {
  const form = formRef.value.getForm();
  formRef.value.setForm({
    ...form,
    user_id: val.props.name,
  });
  queryForm();
};

const getDataboardUser = async () => {
  try {
    const res = await getDataboardUserList();
    personnel_list.value = res.data;
    activeName.value = res.data[0].user_id;
    formRef.value.setForm({
      user_id: res.data[0].user_id,
    });
    queryForm();
  } catch (e) {
    throw Error(e);
  }
};

const queryForm = async () => {
  loading.value = true;
  try {
    const form = formRef.value.getQueryForm();
    const res = await getDataboardElectronicList(form);
    tableData.value = res.data.map((i) => {
      i.images_user_task = i.images_user_task || {
        handle_sort: "",
        handle_time: "",
      };
      i.is_week = filterAssignmentTime(form.assignment_time_start, i.assignment_time_end);
      return i;
    });
    loading.value = false;
  } catch (e) {
    loading.value = false;
    throw Error(e);
  }
};
onMounted(() => {
  getDataboardUser();
});

// 是否分配周期内完成
const comparisonTime = (row) => {
  const process_time = new Date(row.process_time).getTime();
  const assignment_time_end = new Date(row.assignment_time_end).getTime();
  const is_finsh = process_time <= assignment_time_end;
  return process_time && is_finsh ? "是" : "否";
};

// 按照人维度修改
const changeUserRow = async (row) => {
  try {
    const res = await userTaskInfo({
      task_id: row.id,
      handle_sort: row.images_user_task.handle_sort,
      user_id: activeName.value,
      mode: 3,
      handle_time: row.images_user_task.handle_time,
    });
    ElMessage.success("修改成功");
    query();
  } catch (e) {
    throw Error(e);
  }
};

// 按照任务维度修改
const changeTaskRow = async (row) => {
  try {
    const res = await editTaskInfo({
      task_id: row.id,
      handle_remark: row.handle_remark,
      user_id: activeName.value,
      mode: 3,
      is_exceed_task: row.is_exceed_task,
      converted_quantity: row.converted_quantity,
    });
    ElMessage.success("修改成功");
    query();
  } catch (e) {
    throw Error(e);
  }
};

// 环境电子拖拽排序
const handleSort = async () => {
  try {
    const sort = tableData.value.map((item, index) => {
      return {
        task_id: item.id,
        sort: index + 1,
        user_id: activeName.value,
      };
    });
    const res = await eletronicSort({ sort });
    ElMessage.success("保存成功");
    query();
  } catch (e) {
    throw Error(e);
  }
};

// 任务认领
const handleClaimTask = (row) => {
  imagesAssignmentClaimTask({ task_id: [row.id] })
    .then((res) => {
      ElMessage.success("保存成功");
      query();
    })
    .catch((e) => {
      throw Error(e);
    });
  // const res = await imagesAssignmentClaimTask({ task_id: [row.id] })
  // console.log(res);
  // try {

  //   const res = await claimTask({ task_id: [row.id] })
  //   console.log(res);
  //   ElMessage.success('保存成功')
  //   setTimeout(()=>{
  //     query()
  //   })
  // } catch (e) {
  //   throw Error(e)
  // }
};

const refCheckImage = ref();
const checkImageFun = (row) => {
  if (!row.uploaded_image_count) {
    return;
  }
  refCheckImage?.value.open(row.id);
};

const rowClassName = ({ row }) => {
  if (row.is_week) {
    return "current-bg";
  }
  return "";
};

const filterAssignmentTime = (assignment_time_start, date) => {
  // 将传入的时间按照中国时区调整为 Date 对象
  const start = new Date(assignment_time_start);
  const end = new Date(date);

  // 获取今天是本周的第几天（0代表周日，1代表周一，以此类推）
  const currentDay = start.getDay();

  // 获取本周的第一天（周一）的日期
  const firstDayOfWeek = new Date(start);
  firstDayOfWeek.setDate(start.getDate() - currentDay + (currentDay === 0 ? -6 : 1));
  firstDayOfWeek.setHours(0, 0, 0, 0);

  // 获取本周的最后一天（周日）的日期
  const lastDayOfWeek = new Date(start);
  lastDayOfWeek.setDate(start.getDate() - currentDay + 7);
  lastDayOfWeek.setHours(23, 59, 59, 999);

  // 检查传入的日期是否在本周范围内
  return start >= firstDayOfWeek && end <= lastDayOfWeek;
};

const startDate = (date) => {
  if (date) {
    // 将传入的日期设置为周一
    date = new Date(date);
    date.setDate(date.getDate() - date.getDay() + 1);
  }
  return date;
};

const diaLog = ref();
const handleBatch = (type, row) => {
  const records = [row.id];
  diaLog.value.open(type, records);
};
</script>
<style lang="scss">
.current-bg {
  background-color: #fef6e7 !important;
}
</style>
